﻿using System.Collections.Generic;
using System.Threading;

namespace Chimp.Core
{
    public class ChimpJob
    {
        public static Thread T_JobSystem;
        public static List<ChimpJob> Running = new List<ChimpJob>();
        public static Mutex M_JobSystem;

        public ChimpJob()
        {
            JobDone = false;
            T = null;
            P = ThreadPriority.Normal;
            Running.Add(this);
            M = new Mutex();
        }

        public Thread T { get; set; }
        public ThreadPriority P { get; set; }
        public bool JobDone { get; set; }

        public Mutex M { get; set; }
        public bool Locked { get; set; }

        public static void InitJobSystem()
        {
            M_JobSystem = new Mutex();
            T_JobSystem = new Thread(THREAD_JobSystem);
            //    T_JobSystem.Start();
        }

        public static void THREAD_JobSystem()
        {
            while (true)
            {
                M_JobSystem.WaitOne();
                foreach (ChimpJob j in Running)
                {
                    if (!j.T.IsAlive)
                    {
                        j.JobDone = true;
                        Running.Remove(j);
                        break;
                    }
                }
                M_JobSystem.ReleaseMutex();
                Thread.Sleep(8);
            }
        }

        public void Lock()
        {
            Locked = true;
            M.WaitOne();
        }

        public void Release()
        {
            M.ReleaseMutex();
            Locked = false;
        }

        public void BeginJob()
        {
            T = new Thread(PerformJob);
            T.Priority = P;
            T.IsBackground = true;
            T.Start();
        }

        public virtual void PerformJob()
        {
        }
    }
}